package com.ps.service.sys;

import com.ps.enumeration.ResourceTypeEnum;
import com.ps.mapper.SysResourceMapper;
import com.ps.model.entity.SysResource;
import com.ps.model.entity.SysRole;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SysResourceService {

    @Resource
    private SysResourceMapper mapper;

    public List<SysResource> getAll() {
        return mapper.selectList(null);
    }

    public List<SysResource> getEnableApi() {
        return getEnableResourceTree(null, i -> i.getType().equals(ResourceTypeEnum.API.getCode()));
    }


    public List<SysResource> getResourceByRole(SysRole role) {
        if (role == null) {
            return Collections.emptyList();
        }

        String ids = role.getResourceId();

        if (StringUtils.isEmpty(ids)) {
            return Collections.emptyList();
        }

        return getEnableResourceTree(ids, i -> {
            Integer type = i.getType();
            // 只返回页面菜单和接口权限，其他的所有角色都有 ! ! !
            return !type.equals(ResourceTypeEnum.ROOT.getCode())
                    && !type.equals(ResourceTypeEnum.FOLDER.getCode());
        });
    }

    /**
     * 获取路径经过叠加且以启用的resource列表
     *
     * @param ids       resource的id集合，逗号隔开，传入null则返回全部
     * @param predicate 额外的过滤条件，传入null则不进行额外判断
     */
    private List<SysResource> getEnableResourceTree(String ids, Predicate<SysResource> predicate) {
        return mapper
                .selectChildren(ids)
                .stream()
                .filter(r -> {
                    if (!r.isEnable() || predicate != null && !predicate.test(r)) {
                        return false;
                    }

                    String path = r.getPath();
                    int index = path.lastIndexOf("//");
                    if (index != -1 && !path.startsWith("http")) {
                        //去掉'//'前拼接的父节点的path
                        r.setPath(path.substring(index + 1));
                    }

                    return true;
                })
                .collect(Collectors.toList());
    }


}
